
 /*
 * All rights Reserved, Copyright (C) Aisino LIMITED 2019
 * FileName: IndexController.java
 * Version:  1.0
 * Modify record:
 * NO. |     Date       |    Name        |      Content
 * 1   | 2019年3月27日        | Aisino)Jack    | original version
 */
package com.jack.hhitseat.controller;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.jack.hhitseat.bean.InfoSearch;
import com.jack.hhitseat.bean.Log;
import com.jack.hhitseat.bean.LogSearch;
import com.jack.hhitseat.bean.Login;
import com.jack.hhitseat.bean.Search;
import com.jack.hhitseat.bean.Seat;
import com.jack.hhitseat.bean.SeatInfo;
import com.jack.hhitseat.bean.Student;
import com.jack.hhitseat.bean.User;
import com.jack.hhitseat.model.ResultMap;
import com.jack.hhitseat.service.HttpClient;
import com.jack.hhitseat.service.impl.GinfoLogService;
import com.jack.hhitseat.service.impl.HhitService;
import com.jack.hhitseat.service.impl.LoginServiceImpl;
import com.jack.hhitseat.service.impl.SearchService;
import com.jack.hhitseat.service.impl.SeatService;
import com.jack.hhitseat.service.impl.UserServiceImpl;
import com.jack.hhitseat.utils.MyUtils;

/**
 * class name: IndexController <BR>
 * class description: please write your description <BR>
 * @version 1.0  2019年3月27日 上午10:28:50
 * @author Aisino)JackWei
 */
@Controller
public class IndexController {
	@Autowired
	HttpClient httpClient;
	@Autowired
	private UserServiceImpl userService;
	@Autowired
	private LoginServiceImpl loginService;
	@Autowired
	private SearchService searchService;
	@Autowired
	private SeatService seatService;
	@Autowired 
	private HhitService hhitService;
	
	private static String SESSION = "LOGIN_ERR";

	private ResultMap resultMap = new ResultMap();
	private final Logger logger = LoggerFactory.getLogger(IndexController.class);
	  
	  
	@RequestMapping(value="/index")
	public String index() {		
		return "zc";
	}
	
	@RequestMapping(value="/reg")
	@ResponseBody
	public Object regist(String u, String p,String em,
			String zw1, String zw2, String zw3,
			String ip, String cname) {
		
		if(!MyUtils.isEmail(em)) {
			return resultMap.fail().message("用户邮箱地址有问题！");
		}
		
		List<User> users = userService.getUserByNum(u);
		if(users.size()>0) {
			return resultMap.fail().message("该学号已经被注册！");
		}
		String seat = "";
		if(!zw1.contains("选择")) {
			seat+=zw1;
		}else {
		    return resultMap.fail().message("第一个座位必选！");
		}
		
		final int COUNT = 500;
   	 	String url = "http://seat.hhit.edu.cn/ClientWeb/pro/ajax/login.aspx"; 
		  MultiValueMap<String, Object> params = new LinkedMultiValueMap<String, Object>();
		  String sjc = System.currentTimeMillis()+"";
		  
		  params.add("act","dlogin");
		  params.add("number", "0");
		  params.add("id", u); 
		  params.add("pwd", p); 
		  params.add("role", "512");
		  params.add("_nocache", sjc);
		  
		ResponseEntity<String> response =  HttpClient.login2wx(url, null, params);
		String session = response.getHeaders().toString().split("ASP.NET_SessionId=")[1].split("; path=/; ")[0];
		String body = null;
		int i = 0;
		
		for (i = 1; i <= COUNT; i++) {
			body = response.getBody();
			if(!body.contains("验证码")) {
				SESSION = session;
				if(body.contains("密码")) {
					SESSION = "LOGIN_ERR";
				} 
				break;
			} else {
				httpClient.yzm(session);
				response =  HttpClient.login2wx(url, session, params);
			}
		}

		if(SESSION.equals("LOGIN_ERR")) {
			return resultMap.fail().message("学号密码错误！");
		}
		if(i > COUNT) {
			return resultMap.fail().message("登录超时，请稍后重试！");
		}
		
		try {
			Long firstSeat = Long.valueOf(zw1.split("=")[0]);
			Long stuNum = Long.valueOf(u);
			List<String> seats = userService.listFirstSeat(firstSeat, stuNum);
			if(seats != null && seats.size() > 0) {
				return resultMap.fail().message("首位和其他人重复，请重新选择！");
			}
		}catch (Exception e){
			e.printStackTrace();
			return resultMap.fail().message("首位有问题，请重新选择！");
		}
		
		  User user = new User();
		  try {			  
			  user.setUserName(body.split("\"name\":\"")[1].split("\",\"")[0]);
		  }catch (Exception e) {
			  return resultMap.fail().message("连接服务器错误，请稍后再试！");
		  }
		  user.setEmail(em);
		  user.setIp(ip);
		  user.setStuNum(u);
		  user.setPassword(p);
		  user.setIsdo(1);

		  if(!zw2.contains("选择")) {
			  if(zw1.equals(zw2)) {
				  return resultMap.fail().message("第二个座位和第一个座位重复！");
			  }
			  seat+=","+zw2;
		  }
		  
		  if(!zw3.contains("选择")) {
			  if(zw1.equals(zw3)) {
				  return resultMap.fail().message("第三个座位和第一个座位重复！");
			  }
			  if(zw3.equals(zw2)) {
				  return resultMap.fail().message("第三个座位和第二个座位重复！");
			  }
			  seat+=","+zw3;
		  }
		  
		  user.setSeat(seat);
		  user.setCreateTime(MyUtils.getNowDateTime());
		  
		  userService.addUser(user);
		  
		  return resultMap.success().message("注册成功");
	}
	
	@RequestMapping(value="/switch")
	public String onOff() {
		return "oo";
	}
	
	@RequestMapping(value="/update")
	public String update() {
		return "xg";
	}
	@RequestMapping(value="/demo")
	public String demo() {
		return "demo";
	}
	
	@RequestMapping(value="/toOn")
	@ResponseBody
	public Object toOn(String u, String p,String em,
			String f) {

		Login login = new Login();

		List<User> users = userService.getUserByNum(u);
		
		if(users.size() <= 0) {
			return resultMap.fail().message("此学号没有注册！");
		}
		User user = users.get(0);

		if(!user.getPassword().equals(p)) {
			return resultMap.fail().message("密码输入错误！");
		}else if(!user.getEmail().equals(em)) {
			return resultMap.fail().message("邮箱输入错误！");
		}
		if(f.equals(user.getIsdo()+"")&&f.equals("0")){
			return resultMap.success().message("已经是关闭状态!");
		}else if(f.equals(user.getIsdo()+"")&&f.equals("1")){
			return resultMap.success().message("已经是开启状态!");
		}
		
		int result = -1;
		try {
			login.setUserId(Integer.parseInt(u));
			result = userService.updateIsDo(u, Integer.parseInt(f));
		}catch (Exception e) {
			return resultMap.fail().message("输入参数错误！");
		}
		
		if(f.equals("0") && result ==1) {
			//logger.warn("{}===关闭预约服务成功", user.getUserName());
			login.setIp(user.getUserName()+"---关闭服务");
			login.setLoginTime(MyUtils.getNowDateTime());
			loginService.addLogin(login);
			return resultMap.success().message("关闭预约服务成功");
		}else if(f.equals("1") && result ==1){
			//logger.warn("{}===开启预约服务成功", user.getUserName());
			login.setIp(user.getUserName()+"===开启服务");
			login.setLoginTime(MyUtils.getNowDateTime());
			loginService.addLogin(login);
			return resultMap.success().message("开启预约服务成功");
		}
		return resultMap.success().message("设置成功");
	}
	
	
	@RequestMapping(value="/toUpdate")
	@ResponseBody
	public Object toUpdate(String u, String p,String em,
			String f, String zw1, String zw2, String zw3) {

		Login login = new Login();

		List<User> users = userService.getUserByNum(u);
		
		if(users.size() <= 0) {
			return resultMap.fail().message("此学号没有注册！");
		}
		User user = users.get(0);

		if(!user.getPassword().equals(p)) {
			return resultMap.fail().message("密码输入错误！");
		}else if(!user.getEmail().equals(em)) {
			return resultMap.fail().message("邮箱输入错误！");
		}
		if(0 == user.getIsdo()) {
			return resultMap.fail().message("您还没有开启服务！");
		}

		if(f.equals("0")) {
			try {
				Long firstSeat = Long.valueOf(zw1.split("=")[0]);
				Long stuNum = Long.valueOf(u);
				List<String> seats = userService.listFirstSeat(firstSeat, stuNum);
				if(seats != null && seats.size() > 0) {
					return resultMap.fail().message("首位和其他人重复，请重新选择！");
				}
			}catch (Exception e){
				return resultMap.fail().message("首位有问题，请先点击查询！");
			}
			 String seat = "";
			  if(!zw1.contains("选择")) {
				  seat+=zw1;
			  }else {
				  return resultMap.fail().message("第一个座位必选！");
			  }
			  if(!zw2.contains("选择")) {
				  if(zw1.equals(zw2)) {
					  return resultMap.fail().message("第二个座位和第一个座位重复！");
				  }
				  seat+=","+zw2;
			  }
			  if(!zw3.contains("选择")) {
				  if(zw1.equals(zw3)) {
					  return resultMap.fail().message("第三个座位和第一个座位重复！");
				  }
				  if(zw3.equals(zw2)) {
					  return resultMap.fail().message("第三个座位和第二个座位重复！");
				  }
				  seat+=","+zw3;
			  }
			  boolean flag = userService.updateSeat(u, seat);
			  if(flag) {
				  login.setUserId(Integer.parseInt(user.getStuNum()));
				  login.setIp(user.getUserName()+"+++修改座位");
				  login.setLoginTime(MyUtils.getNowDateTime());
				  loginService.addLogin(login);
				  return resultMap.success().message("修改成功");
			  }
			return resultMap.fail().message("修改失败");
		}else if(f.equals("1")){
			return resultMap.success().message(user.getSeat());
		}else {
			return resultMap.fail().message("参数错误！");
		}
	}
	
	@RequestMapping(value="/fa")
	public String fa() {
		return "fontawesome";
	}
	
	@RequestMapping(value="/search")
	public String search(Model model) {
		Integer cc = 0;
		Integer ac = 0;
		Integer c101 = 0;
		Integer a101 = 0;
		Integer c104 = 0;
		Integer a104 = 0;
		Integer c201 = 0;
		Integer a201 = 0;
		Integer c202 = 0;
		Integer a202 = 0;
		Integer c204 = 0;
		Integer a204 = 0;
		Integer c301 = 0;
		Integer a301 = 0;
		Integer c303 = 0;
		Integer a303 = 0;
		Integer c401 = 0;
		Integer a401 = 0;
		Integer c403 = 0;
		Integer a403 = 0;
		Integer c501 = 0;
		Integer a501 = 0;
		Integer c504 = 0;
		Integer a504 = 0;
		
		String d = MyUtils.getNowDateYMD();
		String sjc = System.currentTimeMillis()+"";
		
		String floors[] = {"100455346","100455348","100455578",
				"100455353","100455582","100455588","100455590",
				"100455592","100455594","100455596","100455598",};
		
		for(String sname : floors) {
			String getUrl = "http://seat.hhit.edu.cn/ClientWeb/pro/ajax/device.aspx?byType=devcls&classkind=8&display=fp&md=d&room_id=" + sname
					+"&purpose=&selectOpenAty=&cld_name=default&date=" + d
					+"&fr_start=06%3A00&fr_end=22%3A00&act=get_rsv_sta&_=" + sjc;
			Map<String, Integer> map = save(getUrl);
			cc += map.get("cc");
			ac += map.get("ac");
			
			switch(sname) {
				case "100455346": a101 = map.get("ac");; c101 = map.get("cc");;break;
				case "100455348": a104 = map.get("ac");; c104 = map.get("cc");;break;
				case "100455578": a201 = map.get("ac");; c201 = map.get("cc");;break;
				case "100455353": a202 = map.get("ac");; c202 = map.get("cc");;break;
				case "100455582": a204 = map.get("ac");; c204 = map.get("cc");;break;
				case "100455588": a301 = map.get("ac");; c301 = map.get("cc");;break;
				case "100455590": a303 = map.get("ac");; c303 = map.get("cc");;break;
				case "100455592": a401 = map.get("ac");; c401 = map.get("cc");;break;
				case "100455594": a403 = map.get("ac");; c403 = map.get("cc");;break;
				case "100455596": a501 = map.get("ac");; c501 = map.get("cc");;break;
				case "100455598": a504 = map.get("ac");; c504 = map.get("cc");;break;
			}
		}
		model.addAttribute("aa", seatService.countDay(d, d+" 24:59:59"));
		model.addAttribute("cc", cc);
		model.addAttribute("ac", ac);
		model.addAttribute("a101", a101);
		model.addAttribute("c101", c101);
		model.addAttribute("a104", a104);
		model.addAttribute("c104", c104);
		model.addAttribute("a201", a201);
		model.addAttribute("c201", c201);
		model.addAttribute("a202", a202);
		model.addAttribute("c202", c202);
		model.addAttribute("a204", a204);
		model.addAttribute("c204", c204);
		model.addAttribute("a301", a301);
		model.addAttribute("c301", c301);
		model.addAttribute("a303", a303);
		model.addAttribute("c303", c303);
		model.addAttribute("a401", a401);
		model.addAttribute("c401", c401);
		model.addAttribute("a403", a403);
		model.addAttribute("c403", c403);
		model.addAttribute("a501", a501);
		model.addAttribute("c501", c501);
		model.addAttribute("a504", a504);
		model.addAttribute("c504", c504);
		return "search";
	}
	
	private Map<String, Integer> save(String getUrl) {
		Map<String, Integer> map = new HashMap<>();
		Integer cc = 0;
		Integer ac = 0;
		StringBuffer sb = new StringBuffer();
		
		try {
		     InputStreamReader isr = null;
		     BufferedReader br = null;
		     URL url = new URL(getUrl);
		     URLConnection urlConnection = url.openConnection();
		     urlConnection.setAllowUserInteraction(false);
		     urlConnection.setConnectTimeout(30000);
			 urlConnection.setReadTimeout(30000);
		     isr = new InputStreamReader(url.openStream());
		     br = new BufferedReader(isr);
		     String line;
		     while ((line = br.readLine()) != null){
		        sb.append(line);
		     }
		}catch(Exception e){
			e.printStackTrace();
		}
		String json = sb.toString();
		json = json.split("\"data\":")[1].split(",\"ext\":null}")[0];
		List<SeatInfo> infos = new ArrayList<>();
		infos = JSON.parseArray(json, SeatInfo.class);

		for(SeatInfo info : infos) {
			if(info.getTs().size() == 0) {
				continue;
			}else {
				for(Student st : info.getTs()) {
					Seat seat = new Seat();
					seat.setAccno(st.getAccno());
					seat.setCreateTime(MyUtils.getNowDateTime());
					seat.setDevId(info.getDevId());
					seat.setDevName(info.getDevName());
					seat.setEnd(st.getEnd());
					seat.setOwner(st.getOwner());
					seat.setStart(st.getStart());
					seat.setState(st.getState());
					//实时查询，然后插入数据库
					if(seatService.count(seat.getDevId(), seat.getAccno(), seat.getStart()) <= 0) {
						seatService.insert(seat);
					}
					if(seat.getState().equals("doing")) {
						cc++;
					}
					ac++;
				}
			}
		}
		
		map.put("cc", cc);
		map.put("ac", ac);
		return map;
	}
	
	@RequestMapping(value="/get")
	@ResponseBody
	public Object get(String sid, String f, String sname, String ip) {
		if(null == sid || null == f || null == sname || null == ip) {
			resultMap.fail().message("查询参数有问题！");
			return resultMap;
		}
		
		String d = MyUtils.getNowDateYMD();
		String sjc = System.currentTimeMillis()+"";
		
		if(f.equals("0")) {
			d = MyUtils.getNextDate();
		}
		Search search = new Search();
		search.setIp(ip);
		search.setSdate(d);
		search.setSeat(sname);
		search.setContent(sid);
		search.setCreateTime(MyUtils.getNowDateTime());
		searchService.save(search);
		
		if(sname.contains("西101")) {
			sname = "100455346";
		} else if(sname.contains("西104")) {
			sname = "100455348";
		} else if(sname.contains("西201")) {
			sname = "100455578";
		} else if(sname.contains("东202")) {
			sname = "100455353";
		} else if(sname.contains("西204")) {
			sname = "100455582";
		} else if(sname.contains("西301")) {
			sname = "100455588";
		} else if(sname.contains("西303")) {
			sname = "100455590";
		} else if(sname.contains("西401")) {
			sname = "100455592";
		} else if(sname.contains("西403")) {
			sname = "100455594";
		} else if(sname.contains("西501")) {
			sname = "100455596";
		} else if(sname.contains("西504")) {
			sname = "100455598";
		} 
		
		String getUrl = "http://seat.hhit.edu.cn/ClientWeb/pro/ajax/device.aspx?byType=devcls&classkind=8&display=fp&md=d&room_id=" + sname
				+"&purpose=&selectOpenAty=&cld_name=default&date=" + d
				+"&fr_start=06%3A00&fr_end=22%3A00&act=get_rsv_sta&_=" + sjc;

		StringBuffer sb = new StringBuffer();
		Long s = System.currentTimeMillis();
		try {
		   InputStreamReader isr = null;
		   BufferedReader br = null;
		   URL url = new URL(getUrl);
		   URLConnection urlConnection = url.openConnection();
		   urlConnection.setAllowUserInteraction(false);
		   urlConnection.setConnectTimeout(30000);
		   urlConnection.setReadTimeout(30000);
		   isr = new InputStreamReader(url.openStream());
		   br = new BufferedReader(isr);
		   String line;
		   while ((line = br.readLine()) != null){
		      sb.append(line);
		   }
		}catch(Exception e){
			resultMap.fail().message("连接超时，请稍后再试！");
		}
		logger.warn("实时请求延迟ms====={}", (s-System.currentTimeMillis()));
		
		String json = sb.toString();
		json = json.split("\"data\":")[1].split(",\"ext\":null}")[0];
		List<SeatInfo> infos = new ArrayList<>();
		infos = JSON.parseArray(json, SeatInfo.class);

		for(SeatInfo info : infos) {
			if(info.getTs().size() == 0) {
				continue;
			}else if(info.getDevId().equals(sid)) {
				return info;
			}
		}
		return resultMap.fail().message("此座位无人！");
	}
	
	@RequestMapping(value="/log")
	public String log() {
		return "log";
	}
	
	@RequestMapping(value="/getLog")
	@ResponseBody
	public Object getLog(LogSearch logSearch) {
		
		if(logSearch.getIp()==null || logSearch.getLimit() <0 || logSearch.getPage()<0) {
			return "参数错误";
		}
		
		Search search = new Search();
		search.setIp(logSearch.getIp());
		if(!logSearch.getSname().contains("选择")) {	
			search.setSeat(logSearch.getSname());
		}
		if(!StringUtils.isEmpty(logSearch.getStart()) || !StringUtils.isEmpty(logSearch.getEnd())) {			
			search.setSdate(logSearch.getStart() + "~" + logSearch.getEnd());
		}
		search.setContent(logSearch.getContent()+ " " + logSearch.getPage() +" , "+logSearch.getLimit());
		search.setCreateTime(MyUtils.getNowDateTime());
		searchService.save(search);
		
		return seatService.list(logSearch);
	}
	
	@RequestMapping(value="/info")
	public String info() {
		return "info";
	}
	
	@RequestMapping(value="/getInfo")
	@ResponseBody
	public Object getInfo(InfoSearch infoSearch) {
		if(infoSearch.getIp()==null || infoSearch.getLimit() <0 || infoSearch.getPage()<0) {
			return "参数错误";
		}
		logger.warn("查询用户信息：IP：{}===城市:{}===ACCNO：{}===姓名：{}===学号：{}",infoSearch.getIp(), 
				infoSearch.getCity(),
				infoSearch.getAccno(), 
				infoSearch.getName(), 
				infoSearch.getSno());
		
		return hhitService.list(infoSearch);
	}
}
